
function setPredecessorFieldsVisibility() {
    var relationType = $('#relation_relation_type');
    if (relationType.val() == "precedes" || relationType.val() == "follows") {
        $('#predecessor_fields').show();
    } else {
        $('#predecessor_fields').hide();
    }
}

/**
 * 初始化多个值的自动完成字段
 * @param {string} fieldId - 输入字段的ID
 * @param {string} url - 自动完成的数据源URL
 * @param {Object} options - 额外的自动完成选项
 */
function multipleAutocompleteField(fieldId, url, options) {
	function split(val) {
		return val.split(/,\s*/);
	}

	function extractLast(term) {
		return split(term).pop();
	}

	$(document).ready(function () {
		$('#' + fieldId).autocomplete($.extend({
			source: function (request, response) {
				$.getJSON(url, {
					issueId: extractLast(request.term)
				}, function(result) {
                    console.log("result",result);
                    if(result.code == 0 && result.data.length > 0){
                        // 操作结果数据：映射到自动完成组件需要的格式
                        var processedData = $.map(result.data, function(item) {
                            console.log("item",item);
                            if(item){
                                var label = item.trackerName + " #" + item.id + ": " + item.subject;
                                return {
                                    label: label,  // 显示文本 Support #3511: 测试问题0925111
                                    value: item.id,           // 实际值
                                    originalData: item        // 保留原始数据供后续使用
                                };
                            }
                            response([]);
                        });
                        response(processedData); // 传递处理后的数据
                    }else{
                        response([]);
                    }
				});
			},
			minLength: 2,
			position: {collision: "flipfit"},
			search: function () {
				// 对于relation_issue_to_id字段，修改其span中的i标签样式
				if (fieldId === 'relation_issue_to_id') {
					$('#' + fieldId).prev('span').find('i').removeClass('fa fa-search').addClass('fa fa-spinner fa-spin');
				}
			},
			response: function () {
				// 对于relation_issue_to_id字段，恢复其span中的i标签样式
				if (fieldId === 'relation_issue_to_id') {
					$('#' + fieldId).prev('span').find('i').removeClass('fa fa-spinner fa-spin').addClass('fa fa-search');
				}
			},
			select: function (event, ui) {
				var terms = split(this.value);
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push(ui.item.value);
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				return false;
			}
		}, options));
		$('#' + fieldId).addClass('autocomplete');
	});
}

// 添加关联关系
function addRelation() {
	var issueId = $('#current-issue-id').val();
	var relationType = $('#relation_relation_type').val();
	var issueToId = $('#relation_issue_to_id').val();
	var delay = $('#relation_delay').val();
	
	// 验证必填字段
	if (!issueToId || !issueToId.trim()) {
		$.modal.alertError("请输入要关联的问题ID");
		return;
	}
	
	// 构建提交数据
	var formData = {
		issueId: issueId,
		relationType: relationType,
		issueToId: issueToId.trim()
	};
	
	// 如果选择了需要延期时间的类型，添加延期时间
	if (relationType === 'precedes' || relationType === 'follows') {
		if (!delay || !delay.trim()) {
			$.modal.alertError("请输入延期时间");
			return;
		}
		formData.delay = delay.trim();
	}
	
	// 禁用按钮防止重复提交
	var submitBtn = $('input[name="commit"]');
	submitBtn.prop('disabled', true);
	$.ajax({
		url: ctx + "issue/relation/add/" + issueId,
		type: "POST",
		data: formData,
		dataType: "json",
		success: function(result) {
			if (result.code == 0) {
                if(result.data.length > 0){

				}else{
                }
                $.modal.msgSuccess("关联关系添加成功", modal_status.SUCCESS);
				// 清空表单
				$('#relation_issue_to_id').val('');
				$('#relation_delay').val('');
				$('#new-relation-div').hide();
				loadRelationsForTable(issueId);
			} else {
				$.modal.alertError(result.msg || "添加关联关系失败");
			}
		},
		error: function(xhr, status, error) {
			$.modal.alertError("请求失败，请稍后再试");
			console.error("Error adding relation:", error);
		},
		complete: function() {
			// 恢复按钮状态
			submitBtn.prop('disabled', false);
		}
	});
}
		
// 加载关联问题列表
function loadRelations(issueId) {
    $.ajax({
        url: ctx + "issue/relation/list/" + issueId,
        type: "GET",
        dataType: "json",
        success: function(result) {
            if (result.code == 0) {
                displayRelations(result.data);
            } else {
                $('#relations-list').html('<div class="text-center"><small class="text-muted">加载失败</small></div>');
            }
        },
        error: function() {
            $('#relations-list').html('<div class="text-center"><small class="text-muted">加载失败</small></div>');
        }
    });
}

// 加载关联问题列表并显示在表格中
function loadRelationsForTable(issueId) {
    $.ajax({
        url: ctx + "issue/relation/list/" + issueId,
        type: "GET",
        dataType: "json",
        success: function(result) {
            if (result.code == 0) {
                displayRelationsInTable(result.data);
            } else {
                $('.relation-issues-wrapper').html('<div class="text-center"><small class="text-muted">加载失败</small></div>');
            }
        },
        error: function() {
            $('.relation-issues-wrapper').html('<div class="text-center"><small class="text-muted">加载失败</small></div>');
        }
    });
}

// 显示关联问题列表
function displayRelations(relations) {
    var relationList = $('#relations-list');
    var relationCount = $('#relation-count-num');
    
    if (relations && relations.length > 0) {
        var html = '';
        relations.forEach(function(relation) {
            // 根据关联关系类型确定显示哪个问题
            var issue = relation.issueTo || relation.issueFrom;
            if (issue) {
                var relationTypeText = getRelationTypeText(relation.relationType);
                var relationTypeClass = getRelationTypeClass(relation.relationType);
                
                html += '<div class="sidebar-relation-item">';
                html += '<div class="relation-info">';
                html += '<span class="label ' + relationTypeClass + ' relation-type-badge">' + relationTypeText + '</span>';
                html += '<a href="javascript:void(0);" class="relation-issue-link" onclick="openIssueDetail(' + issue.id + ')">';
                html += '<i class="fa fa-bug text-muted"></i> ';
                html += '<span class="relation-issue-subject">' + (issue.subject || '未知问题') + '</span>';
                html += ' <small class="text-muted">#' + issue.id + '</small>';
                html += '</a>';
                html += '</div>';
                html += '<div class="relation-actions">';
                html += '<button type="button" class="btn btn-xs btn-danger" onclick="removeRelation(' + relation.id + ')">删除</button>';
                html += '</div>';
                html += '</div>';
            }
        });
        relationList.html(html);
        relationCount.text(relations.length);
    } else {
        relationList.html('<div class="text-center"><small class="text-muted">暂无关联问题</small></div>');
        relationCount.text('0');
    }
}

// 获取关联类型文本
function getRelationTypeText(relationType) {
    var typeMap = {
        'relates': '关联',
        'duplicates': '重复',
        'blocks': '阻塞',
        'follows': '跟随',
        'precedes': '前置'
    };
    return typeMap[relationType] || relationType;
}

// 获取关联类型样式类
function getRelationTypeClass(relationType) {
    var classMap = {
        'relates': 'label-default',
        'duplicates': 'label-warning',
        'blocks': 'label-danger',
        'follows': 'label-info',
        'precedes': 'label-success'
    };
    return classMap[relationType] || 'label-default';
}

// 打开关联问题模态框
function openRelationModal(issueId) {
    var url = ctx + "issue/relation/modal/" + issueId;
    $.modal.open("添加关联问题", url, "800");
}

// 删除关联关系
function removeRelation(relationId) {
    $.modal.confirm("确定要删除这个关联关系吗？", function() {
        $.ajax({
            url: ctx + "issue/relation/remove/" + relationId,
            type: "POST",
            dataType: "json",
            success: function(result) {
                if (result.code == 0) {
                    $.modal.msgSuccess("删除成功");
                    // 重新加载关联问题列表
                    var currentIssueId = $('#current-issue-id').val();
                    loadRelations(currentIssueId);
                    loadRelationsForTable(currentIssueId);
                } else {
                    $.modal.msgError(result.msg);
                }
            },
            error: function() {
                $.modal.msgError("删除失败，请稍后再试");
            }
        });
    });
}

// 动态加载关联问题到页面表格
function displayRelationsInTable(relations) {
    var tableBody = $('.relation-issues-wrapper tbody');
    var wrapper = $('.relation-issues-wrapper');
    
    if (relations && relations.length > 0) {
        var html = '';
        relations.forEach(function(relation) {
            // 根据关联关系类型确定显示哪个问题
            var issue = relation.issueTo || relation.issueFrom;
            if (issue) {
                var relationTypeText = getRelationTypeTextForTable(relation.relationType);
                var relationClass = 'rel-' + relation.relationType;
                
                html += '<tr id="relation-' + relation.id + '" class="hascontextmenu ' + relationClass + '">';
                html += '<td class="subject">' + relationTypeText + ' ' + (issue.project ? issue.projectName + '(' + issue.project.customerName + ')' + '»' : '') + ' <a href="javascript:void(0)" onclick="openIssueTab(' + issue.id + ')">' + issue.trackerName + ' #' + issue.id + ': ' + (issue.subject || '未知问题')  + '</a></td>';
                html += '<td class="status">' + (issue.statusName || '') + '</td>';
                html += '<td class="assigned_to">' + (issue.assignedToName ? '<a class="user active" href="/users/' + issue.assignedToId + '">' + issue.assignedToName + '</a>' : '') + '</td>';
                html += '<td class="start_date">' + (issue.startDate || '') + '</td>';
                html += '<td class="due_date">' + (issue.dueDate || '') + '</td>';
                html += '<td class="done_ratio">';
                    html += '<div class="progress progress-custom-width" style="width: 100%;">';
                    html += '<div style="width: ' + issue.doneRatio + '%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="' + issue.doneRatio + '" role="progressbar" class="progress-bar">';
                    html += '<span class="' + (issue.doneRatio <= 10 ? 'text-black' : '') + '">' + issue.doneRatio + '%</span>';
                    html += '</div>';
                    html += '</div>';
                html += '</td>';
                html += '<td class="buttons">';
                html += '<a title="删除关联" class="fs-16" href="javascript:void(0);" onclick="removeRelation(' + relation.id + ')"><i class="fa fa-chain-broken"></i></a>';
                html += '</td>';
                html += '</tr>';
            }
        });
        
        // 确保表格容器可见并更新内容
        if (wrapper.length === 0) {
            // 如果容器不存在，需要创建
            var relationSection = $('div:has(h4:contains("相关的需求"))');
            relationSection.append('<div class="relation-issues-wrapper"><table class="list issues odd-even"><tbody>' + html + '</tbody></table></div>');
        } else {
            tableBody.html(html);
            wrapper.show();
        }
    } else {
        // 如果没有关联问题，显示空提示
        if (wrapper.length === 0) {
            var relationSection = $('div:has(h4:contains("相关的需求"))');
            // relationSection.append('<div class="relation-issues-wrapper"><div class="text-center"><small class="text-muted">暂无关联问题</small></div></div>');
        } else {
            // wrapper.html('<div class="text-center"><small class="text-muted">暂无关联问题</small></div>');
            tableBody.html('');
            wrapper.show();
        }
    }
}

// 获取关联类型文本（用于表格显示）
function getRelationTypeTextForTable(relationType) {
    var typeMap = {
        'relates': '关联到',
        'duplicates': '重复',
        'duplicated': '与其重复',
        'blocks': '阻挡',
        'blocked': '被阻挡',
        'precedes': '优先于',
        'follows': '跟随于',
        'copied_to': '复制到',
        'copied_from': '复制于'
    };
    return typeMap[relationType] || relationType;
}

// 打开问题详情
function openIssueDetail(issueId) {
    var url = prefix + "/" + issueId;
    $.modal.openTab("问题详情", url);
}